package com.hsurosy.hsuchain.nft.base.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring 上下文工具类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-04 18:58
 * @Description
 * @Version: v1.0.0
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 设置 Spring 上下文
     *
     * @param applicationContext Spring 上下文
     * @throws BeansException Bean 异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 根据 Bean 名称获取实例
     *
     * @param name Bean 名称
     * @return Bean 实例
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 根据 Bean 类型获取实例
     *
     * @param <T> Bean 类型
     * @param name Bean 类型的类对象
     * @return Bean 实例
     */
    public static <T> T getBean(Class<T> name) {
        return applicationContext.getBean(name);
    }
}
